// 门店
var db = require("../db/index");
var config = require("../_include/config");
var db_table_name = config.dbname.busShop;
var db_id_prefix = config.dbIdPrefix.busShop;
var helper = require("../_include/helper");

//构造函数
var _con = function(info) {
	var self = this;
	//ID编号
	self._id = db_id_prefix + Math.random().toString(16).substr(2) + (+new Date).toString(16);

	self.state = _con.STATE.未审核;

	//所属的商家
	self.bus_id = info.bus_id;
	if (!self.bus_id) {
		throwCusError("门店必须指定一个所属商家")
	}
	var bus = BusCon.get(self.bus_id);
	if (!bus) {
		throwCusError("找不到门店指定所属商家");
	}

	//拥有此门店的市代
	self.MA_id = info.MA_id;
	if (!self.MA_id) {
		// MA_id为空是属于商家直属的门店
		// throwCusError("门店必须指定一个市代账号")
		// bus._addShop(self._id);
	} else {
		// 属于市代的门店
		var MA = BusMACon.get(self.MA_id);
		if (!MA) {
			throwCusError("门店指定的市代账号无效")
		}
		// MA._addShop(self._id);
	}

	//介绍人
	if (info.introducer) {
		var introducer = UserCon.search(info.introducer);
		if (!introducer) {
			throwCusError("无法根据指定信息找到相关介绍人，请输入电话号码或者邮箱");
		}
		this.introducer_id = introducer._id;
	}

	this.setInfo(info, "no_save");

	self.create_time = +new Date;

	if (!self.MA_id) {
		bus._addShop(self._id);
	} else {
		MA._addShop(self._id);
	}
	db.insert(db_table_name, self);
	console.log("创建了一个门店：", info.city_name);
};
//PS:模块的暴露放在require skill前面，因为二者互相依赖
module.exports = _con;
//技能
_con.prototype = require("./skill");

_con.STATE = {
	"未审核": 0,
	"审核中": 1,
	"审核通过": 2,
	"冻结": -1,
};

//静态方法
_con.get = function(Id) {
	var result = db.find_by_id(db_table_name, Id);
	return _con.getInstance(result);
};
_con.getInstance = function(obj) {
	if (obj) {
		if (!(obj.nojson_able_keys instanceof Array)) { //固定黑名单
			Object.defineProperty(obj, "nojson_able_keys", {
				enumerable: false,
				value: []
			});
		}
		obj.__proto__ = _con.prototype;
	}
	return obj;
};

var UserCon = require("../user/_con");
var BusMACon = require("../bus.MA/_con");
var BusCon = require("../bus/_con");